package com.lzx.adx.report.controller.v1.oppo;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.oppo.OppoRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品：58同城（有道接口）
 * 媒体：趣头条
 */
@RequestMapping("/oppo/kk")
@RestController
@Slf4j
public class OppoKKController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/report")
    public ResponseEntity report(OppoRequest requestParams, HttpServletRequest request) {
        log.info("接收到oppo到夸克的请求参数为{}", JsonUtils.toJsonString(requestParams));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(requestParams);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(requestParams));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(requestParams.getDspId());
        String finalUrl = KkHeper.covertOppoKk(accountDTO, requestParams, reportDTO);
        log.info("账号为{},完整的oppo到夸克请求地址为{}", requestParams.getDspId(), finalUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 完整的oppo到夸克请求地址为，上报的接口，响应的结果为{}", requestParams.getDspId(), body);
        return ResponseEntity.ok(new Result());
    }


    /**
     * 饿了么回传
     *
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId) throws Exception {
        String evenType="1";
        log.info("夸克回调趣头条信息，请求流水号{}", requestId);
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        long currentTimeMillis = System.currentTimeMillis();
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType("0");
            reportDTO.setResultTime(String.valueOf(currentTimeMillis));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,evenType);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getDspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);

        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(accountDTO.getSspApiUrl());
        log.info("趣头条-饿了么转码地址为：{}", decodeUrl);

        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("imei", "");
        reqMap.put("ouId", encode(reportDTO.getOaid().getBytes(StandardCharsets.UTF_8)
                , jsonObject.getString("base64Key")));
        reqMap.put("timestamp", currentTimeMillis);
        reqMap.put("pkg", jsonObject.getString("pkg"));
        reqMap.put("dataType", 1);
        reqMap.put("channel", 1);
        reqMap.put("type", 2);
        reqMap.put("ascribeType", 1);
        reqMap.put("adId", reportDTO.getTagId());
        String resultPams = JSON.toJSONString(reqMap);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json");
        headerMap.put("signature", SecureUtil.md5(resultPams + currentTimeMillis + jsonObject.getString("salt")).toLowerCase());
        headerMap.put("timestamp", String.valueOf(currentTimeMillis));
        log.info("账号为{}夸克到oppo请求地址{} 请求头{} 请求参数：{}", reportDTO.getDspId(), accountDTO.getSspApiUrl(), JSON.toJSONString(headerMap), resultPams);
        String result = HttpUtil.createPost(accountDTO.getSspApiUrl())
                .headerMap(headerMap, false)
                .body(resultPams)
                .timeout(5000)
                .execute()
                .body();
        log.info("账号为{}夸克到oppo请求的结果为{}", reportDTO.getDspId(), result);
        return ResponseEntity.ok(new Result());
    }


    public String encode(byte[] data, String base64Key) throws
            GeneralSecurityException {
        final Key dataKey = new SecretKeySpec(Base64.decodeBase64(base64Key),
                "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, dataKey);
        byte[] encryptData = cipher.doFinal(data);
        return Base64.encodeBase64String(encryptData).replaceAll("\r",
                "").replaceAll("\n", "");
    }

}
